package org.smth.search.config.impl;

import com.google.inject.Singleton;

import org.smth.search.config.FetcherConfig;

import java.util.*;

@Singleton
public class HardCodeFetcherConfig implements FetcherConfig {

	private List<String> boards = new ArrayList<String>();

	HardCodeFetcherConfig() {
		boards.addAll(Arrays.asList("java", "familylife", "joke", "worklife", "pielove", "itexpress", "stock", "fund", "palsword", "realestate", "love", "myphoto", "dotnet", "oversea", "graduate", "movie", "houserent", "secondmarket", "advancededu", "autoworld", "age", "notebook"));
	}

	private int current = -1;

	public String getNextBoard() {
		String board;
		try {
			while ((board = getNextBoard1()) == null) {
				Thread.sleep(2000);
			}
		} catch (InterruptedException e) {
			throw new RuntimeException("线程被打断");
		}
		return board;
	}

	private ThreadLocal<String> currentBoard = new ThreadLocal<String>();

	private Map<String, Thread> map = new HashMap<String, Thread>();

	private synchronized String getNextBoard1() {
		String old = currentBoard.get();
		if (old != null) {
			map.remove(old);
			currentBoard.set(null);
		}
		String board = getNextBoard2();
		Thread thread = map.get(board);
		if (thread == null || thread.getState() == Thread.State.TERMINATED) {
			map.put(board, Thread.currentThread());
			return board;
		} else {
			return null;
		}
	}

	private synchronized String getNextBoard2() {
		current++;
		current %= boards.size();
		return boards.get(current).toLowerCase();
	}

	public int getThreadsNum() {
		return 2;
	}
}
